<template>
  <div class="index">
    <head-text titleText="订单管理"></head-text>
    <div class="list-content">
      <div class="filter-area">
        <Search :searchData="searchData" :searchItem="searchItem"></Search>
        <div class="operate-area">
          <el-button @click="exp" plain type="success" size="mini"
            >导出</el-button
          >
          <el-button plain @click="batchSelection" type="danger" size="mini"
            >批量退单</el-button
          >
        </div>
      </div>
      <div class="table-title">
        <span></span>
        <h5>订单列表</h5>
      </div>
      <el-table
        :data="tableData"
        style="width: 100%"
        border
        size="mini"
        v-if="hackReset"
        @selection-change="handleSelectionChange"
      >
        <!-- <el-table-column type="index" width="50" align="center">
        </el-table-column> -->
        <el-table-column
          type="selection"
          width="55"
          align="center"
          :selectable="selectable"
        >
        </el-table-column>
        <el-table-column
          prop="orderSn"
          label="订单号"
          align="center"
          min-width="150"
        >
        </el-table-column>
        <el-table-column
          prop="orderStatus"
          label="订单状态"
          align="center"
          min-width="90"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.orderStatus | orderStatusFilter }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="createTime"
          label="订购日期"
          min-width="150"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="orderPhone"
          label="手机号"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="activityName"
          label="关联活动"
          align="center"
          :show-overflow-tooltip="true"
          width="140"
        >
        </el-table-column>
        <el-table-column
          prop="activityTime"
          label="活动场次"
          align="center"
          min-width="140"
        >
        </el-table-column>
        <el-table-column
          prop="venueFloor"
          label="楼层"
          align="center"
          min-width="70"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.venueFloor | floorFilter }}
            </div>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="remark" label="备注" align="center">
        </el-table-column> -->
        <el-table-column
          prop="orderMoney"
          label="应收金额（元）"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="paymentMoney"
          label="实收金额（元）"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="discountType"
          label="折扣/优惠类型"
          align="center"
          min-width="110"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.discountType | discountFilter }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="discountMoney"
          label="优惠金额（元）"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column
          prop="paymentMethod"
          label="支付方式"
          align="center"
          min-width="90"
        >
          <template slot-scope="scope">
            <div>
              {{ scope.row.paymentMethod | payFilter }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="serialNumber"
          label="支付流水号"
          align="center"
          min-width="110"
        >
        </el-table-column>
        <el-table-column label="商品明细" width="110" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              style="margin: 5px"
              @click="view(scope.row.orderId)"
            >
              查看详情
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
              type="danger"
              style="margin: 5px"
              plain
              size="mini"
              @click="chargeback(scope.row.orderId)"
              v-if="scope.row.orderStatus != 6"
              >手动退单</el-button
            >
            <el-button
              type="danger"
              style="margin: 5px"
              plain
              size="mini"
              @click="closeCheck(scope.row.orderId)"
              v-if="scope.row.orderStatus == 7"
              >关闭订单</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <page
        :nowPage="nowPage"
        :total="total"
        :limit="limit"
        :resetPage="nowPage"
        @pageChange="onPageChange"
        @sizeChange="onSizeChange"
        v-if="pageReset"
      />
    </div>
    <dialog-com :dialogObj="dialogObj" @reflash="getList"></dialog-com>
  </div>
</template>

<script>
import Search from "@c/search";
import Cookie from "@u/cookie";
import { _debounce } from "@u/debounce";
import headText from "@c/headText";
import dialogCom from "./dialogCom";
import page from "@c/page";
import {
  getOrderInfoListApi,
  getLocalActivityApi,
  orderExportExcelApi,
  chargebackUApi,
  updateOrderInfoListApi
} from "@s/api";
import {
  FLOORARR2,
  ORDERSTATUSLIST,
  FLOOROBJ2,
  DISCOUNTTYPE,
  PAYTYPE,
  ORDERSTATUS
} from "@u/wordbook";

export default {
  name: "index",
  data() {
    return {
      nowPage: 1,
      total: 0,
      limit: 10,
      pageReset: true,
      hackReset: true,
      activityTimeList: [],
      searchItem: [],
      isHaveFoor:
        JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor == 0
          ? ""
          : JSON.parse(localStorage.getItem("mb_userInfo")).venueFloor,
      multipleSelection: [],
      ActivityList: [],
      floorArr: FLOORARR2,
      orderStatus: ORDERSTATUSLIST,
      dialogObj: {
        title: "",
        orderId: "",
        show: false
      },
      dateTime: [],
      searchData: {
        activityId: "",
        startDate: "",
        endDate: "",
        orderSn: "",
        venueFloor: "",
        orderStatus: "",
        orderPhone: "",
        activityTime: "",
        orderType: "1" //1 餐饮
      },
      tableData: []
    };
  },
  components: {
    headText,
    dialogCom,
    page,
    Search
  },
  mounted() {
    this.getActivityList();
    this.getList();
  },
  created() {
    this.searchItem = [
      {
        type: "daterange",
        label: "订购日期：",
        timeFormat: "yyyy-MM-dd",
        timeList: ["startDate", "endDate"]
      },
      {
        type: "select",
        label: "订单状态：",
        prop: "orderStatus",
        placeholder: "请选择订单状态",
        selectList: this.orderStatus
      },
      {
        type: "select",
        label: "活动：",
        prop: "activityId",
        placeholder: "请选择活动",
        selectList: this.ActivityList
      },
      {
        type: "select",
        label: "活动场次：",
        prop: "activityTime",
        placeholder: "请选择活动场次",
        selectList: this.activityTimeList
      },
      {
        type: "select",
        label: "楼层：",
        prop: "venueFloor",
        placeholder: "请选择楼层",
        selectList: this.floorArr
      },
      {
        type: "input",
        label: "订单号：",
        prop: "orderSn",
        placeholder: "请输入订单号"
      },

      {
        type: "input",
        label: "手机号：",
        prop: "orderPhone",
        placeholder: "请输入手机号"
      }
    ];
    if (this.isHaveFoor) {
      this.searchItem.forEach((item, i) => {
        if (item.prop == "venueFloor") {
          this.searchItem.splice(i, 1);
        }
      });
    }
  },
  //过滤器
  filters: {
    floorFilter(val) {
      return FLOOROBJ2[val];
    },
    discountFilter(val) {
      return DISCOUNTTYPE[val];
    },
    payFilter(val) {
      return PAYTYPE[val];
    },
    orderStatusFilter(val) {
      return ORDERSTATUS[val];
    }
  },
  methods: {
    onPageChange(val) {
      this.nowPage = val;
      this.getList();
    },
    onSizeChange(val) {
      this.nowPage = 1;
      this.limit = val;
      this.getList();
    },
    // 默认禁止选中
    selectable(row) {
      if (row.orderStatus != 6 && row.orderStatus != 7) {
        return true;
      } else {
        return false;
      }
    },
    // 多选函数
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },

    // 活动信息
    getActivityList() {
      getLocalActivityApi().then(res => {
        let newActivityList = [];
        res.list.forEach(item => {
          var newItem = {
            id: item.activityId,
            value: item.activityName,
            activityTimes: JSON.parse(item.activityDates)
          };
          newActivityList.push(newItem);
        });
        this.ActivityList = newActivityList;
        this.searchItem.forEach(item => {
          if (item.prop == "activityId") {
            item.selectList = this.ActivityList;
          }
        });
      });
    },
    // 批量退单操作
    chargeCheck(id) {
      this.chargeback(id, "批量");
    },
    chargeback(id, many = "") {
      this.$confirm("此操作将" + many + "退订该订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let json = {
          ids: [],
          operation: 1 // 1同意 2拒绝退单
        };
        if (id instanceof Array) {
          json.ids = id;
        } else {
          json.ids.push(id);
        }
        chargebackUApi(json).then(res => {
          this.getList();
          let orderInfo = "";
          if (res) {
            if (res == "退款失败") {
              this.$message({
                type: "error",
                dangerouslyUseHTMLString: true,
                message:
                  "<div><h4>退款失败</h4><p style='margin-left:10px'><br />请确认：</p><p style='margin:5px 20px '>1、账号余额是否充足.</p><p style='margin:5px 20px '>2、是否变更过银盒子ID.</p></div>"
              });
            } else {
              if (res.successNum) {
                orderInfo =
                  "退单成功 " +
                  res.successNum +
                  "条，" +
                  "退单失败 " +
                  res.failNum +
                  "条";
              }
              this.$message({
                type: "success",
                message: orderInfo
              });
            }
          } else {
            this.$message({
              type: "success",
              message: "操作成功！"
            });
          }
        });
      });
    },
    // 关闭定单
    closeCheck(id) {
      this.$confirm("此操作将手动关闭该订单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        let json = {
          orderId: id,
          orderStatus: 6 // 6 退单成功
        };
        updateOrderInfoListApi(json).then(() => {
          this.getList();
          this.$message({
            type: "success",
            message: "操作成功！"
          });
        });
      });
    },
    // 批量操作
    batchSelection() {
      if (this.multipleSelection.length > 0) {
        var ids = [];
        this.multipleSelection.forEach(item => {
          ids.push(item.orderId);
        });
        this.chargeCheck(ids);
      } else {
        this.$message({
          type: "warning",
          message: "必须选择至少一项！"
        });
      }
    },
    // 搜索事件
    getDataList(val) {
      this.searchData = val;
      this.nowPage = 1;
      this.limit = 10;
      this.pageReset = false;
      this.$nextTick(() => {
        this.getList();
        this.pageReset = true;
      });
    },
    getList() {
      if (this.isHaveFoor) {
        this.searchData.venueFloor = JSON.parse(
          Cookie.get("mb_userInfo")
        ).venueFloor;
      }
      let json = JSON.parse(JSON.stringify(this.searchData));
      json.page = this.nowPage;
      json.limit = this.limit;
      getOrderInfoListApi(json).then(res => {
        this.hackReset = false;
        this.$nextTick(() => {
          this.tableData = res.list;
          this.total = res.total;
          this.hackReset = true;
        });
      });
    },
    exp: _debounce(function() {
      if (this.isHaveFoor) {
        this.searchData.venueFloor = JSON.parse(
          Cookie.get("mb_userInfo")
        ).venueFloor;
      }
      let json = JSON.parse(JSON.stringify(this.searchData));
      orderExportExcelApi(json, "餐饮商品订单信息表").then(() => {});
    }),
    view(orderId) {
      this.dialogObj.show = true;
      this.dialogObj.orderId = orderId;
      this.dialogObj.title = "订单详情";
    }
  },
  watch: {
    "searchData.activityId"(val) {
      this.searchData.activityTime = "";
      this.activityTimeList = [];
      window.console.log(val);
      if (val) {
        window.console.log(this.ActivityList);
        var newActivityTime = [];
        this.ActivityList.forEach(item => {
          if (item.id == val) {
            item.activityTimes.forEach(v => {
              var newItem = {
                id: v.start,
                value: v.start
              };
              newActivityTime.push(newItem);
            });
          }
        });
        this.activityTimeList = newActivityTime;
        this.searchItem.forEach(item => {
          if (item.prop == "activityTime") {
            item.selectList = this.activityTimeList;
          }
        });
      } else {
        this.searchItem.forEach(item => {
          if (item.prop == "activityTime") {
            item.selectList = this.activityTimeList;
          }
        });
      }
      window.console.log(this.activityTimeList);
    }
  }
};
</script>
<style scoped lang="scss"></style>
